import { SceneElement } from './SceneElement';

/**
 * SceneManager Class
 * 
 * Manages all elements within a scene including backgrounds, characters, and UI elements.
 */
export class SceneManager {
  private elements: Map<string, SceneElement> = new Map();

  /**
   * Adds an element to the scene
   * @param element - The element to add
   */
  public addElement(element: SceneElement): void {
    this.elements.set(element.getId(), element);
  }

  /**
   * Removes an element from the scene
   * @param id - The ID of the element to remove
   */
  public removeElement(id: string): void {
    this.elements.delete(id);
  }

  /**
   * Retrieves an element by ID
   * @param id - The ID of the element to retrieve
   * @returns SceneElement - The element, or undefined if not found
   */
  public getElement(id: string): SceneElement | undefined {
    return this.elements.get(id);
  }

  /**
   * Returns all elements in the scene
   * @returns SceneElement[] - Array of all elements
   */
  public getAllElements(): SceneElement[] {
    return Array.from(this.elements.values());
  }

  /**
   * Reorders elements by their IDs
   * @param newOrder - Array of element IDs in the desired order
   */
  public reorderElements(newOrder: string[]): void {
    // Create a new map with the specified order
    const newElementsMap = new Map<string, SceneElement>();
    
    // Add elements in the new order
    for (const id of newOrder) {
      const element = this.elements.get(id);
      if (element) {
        newElementsMap.set(id, element);
      }
    }
    
    // Add any remaining elements that weren't in the newOrder array
    for (const [id, element] of this.elements) {
      if (!newElementsMap.has(id)) {
        newElementsMap.set(id, element);
      }
    }
    
    this.elements = newElementsMap;
  }

  /**
   * Gets the number of elements in the scene
   * @returns number - The number of elements
   */
  public getElementCount(): number {
    return this.elements.size;
  }

  /**
   * Clears all elements from the scene
   */
  public clearAllElements(): void {
    this.elements.clear();
  }
}